package com.eboss.sbs.activity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.TextView;

import com.eboss.sbs.R;
import com.eboss.sbs.activity.base.BaseActivity;
import com.eboss.sbs.enums.EnumConsts;
import com.eboss.sbs.http.API;
import com.eboss.sbs.http.HttpCallback;
import com.eboss.sbs.model.CaculateMoneyEntity;
import com.eboss.sbs.model.UploadResultEntity;
import com.eboss.sbs.model.db.OrderDetail;
import com.google.gson.reflect.TypeToken;
import com.mytools.tool.utils.LocalParasUtils;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.views.MyDialog;

import org.litepal.crud.DataSupport;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class PayCashActivity extends BaseActivity {

	public static String CACULATE_MONEY_ENTITY = "CACULATE_MONEY_ENTITY";
	
	private static int DOT = -1;
	private static int DEL = -2;
	
	private int real_money = -1;
	
	private CaculateMoneyEntity caculateMoneyEntity;
	private String password;
	private String couponSns;
	private int pointAmount;
	
	private TextView tv_receive_money;
	private TextView tv_return_money;
	
	private int receive_money = 0;
	private int return_money = 0;
	
	private String money_str = "";
	
	private int scanPayType = EnumConsts.ScanPayType.SQB.getType();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mActivity = this;
		setContentView(R.layout.activity_pay_cash);
		super.onCreate(savedInstanceState);
		
		scanPayType = mApp.getLoginEntity().getScanPayType();
		
		password = getIntent().getStringExtra("password");
		couponSns = getIntent().getStringExtra("couponSns");
		pointAmount = getIntent().getIntExtra("pointAmount", 0);
		caculateMoneyEntity = (CaculateMoneyEntity) getIntent().getSerializableExtra(CACULATE_MONEY_ENTITY);
		if(caculateMoneyEntity==null){toast("金额参数错误");finish();return;}
		real_money = caculateMoneyEntity.getRealMoney();
		initView();
	}
	
	private void initView(){
		setTvText(R.id.tv_title, "现金记账计算器");
		
		tv_receive_money = (TextView) findViewById(R.id.tv_receive_money);
		tv_return_money = (TextView) findViewById(R.id.tv_return_money);
		
		display_money();
		
		setTvText(R.id.tv_real_money, StringUtil.getMoneyString(real_money));
		
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);
		
		findViewById(R.id.btn_money_100).setOnClickListener(this);
		findViewById(R.id.btn_money_50).setOnClickListener(this);
		findViewById(R.id.btn_money_20).setOnClickListener(this);
		findViewById(R.id.btn_money_10).setOnClickListener(this);
		findViewById(R.id.btn_money_5).setOnClickListener(this);
		
		findViewById(R.id.tv_num_1).setOnClickListener(this);
		findViewById(R.id.tv_num_2).setOnClickListener(this);
		findViewById(R.id.tv_num_3).setOnClickListener(this);
		findViewById(R.id.tv_num_4).setOnClickListener(this);
		findViewById(R.id.tv_num_5).setOnClickListener(this);
		findViewById(R.id.tv_num_6).setOnClickListener(this);
		findViewById(R.id.tv_num_7).setOnClickListener(this);
		findViewById(R.id.tv_num_8).setOnClickListener(this);
		findViewById(R.id.tv_num_9).setOnClickListener(this);
		findViewById(R.id.tv_num_dot).setOnClickListener(this);
		findViewById(R.id.tv_num_0).setOnClickListener(this);
		findViewById(R.id.tv_num_del).setOnClickListener(this);
		
		findViewById(R.id.tv_num_1).setOnClickListener(this);
		findViewById(R.id.tv_num_2).setOnClickListener(this);
		findViewById(R.id.tv_num_3).setOnClickListener(this);
		findViewById(R.id.tv_num_4).setOnClickListener(this);
		findViewById(R.id.tv_num_5).setOnClickListener(this);
		findViewById(R.id.tv_num_6).setOnClickListener(this);
		findViewById(R.id.tv_num_7).setOnClickListener(this);
		findViewById(R.id.tv_num_8).setOnClickListener(this);
		findViewById(R.id.tv_num_9).setOnClickListener(this);
		findViewById(R.id.tv_num_dot).setOnClickListener(this);
		findViewById(R.id.tv_num_0).setOnClickListener(this);
		findViewById(R.id.tv_num_del).setOnClickListener(this);
		
		findViewById(R.id.btn_submit).setOnClickListener(this);
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.titleback_btn_back:finish();break;
			case R.id.btn_money_100:receive_money=10000;money_str="100.00";display_money();break;
			case R.id.btn_money_50:receive_money=5000;money_str="50.00";display_money();break;
			case R.id.btn_money_20:receive_money=2000;money_str="20.00";display_money();break;
			case R.id.btn_money_10:receive_money=1000;money_str="10.00";display_money();break;
			case R.id.btn_money_5:receive_money=500;money_str="5.00";display_money();break;
			
			case R.id.tv_num_1:key_event(1);break;
			case R.id.tv_num_2:key_event(2);break;
			case R.id.tv_num_3:key_event(3);break;
			case R.id.tv_num_4:key_event(4);break;
			case R.id.tv_num_5:key_event(5);break;
			case R.id.tv_num_6:key_event(6);break;
			case R.id.tv_num_7:key_event(7);break;
			case R.id.tv_num_8:key_event(8);break;
			case R.id.tv_num_9:key_event(9);break;
			case R.id.tv_num_dot:key_event(DOT);break;
			case R.id.tv_num_0:key_event(0);break;
			case R.id.tv_num_del:key_event(DEL);break;
	
			case R.id.btn_submit:doSubmit_pre();break;
			default: break;
		}
		super.onClick(v);
	}
	
	private void key_event(int key){
		if(key>=0&&key<=9){
			if(Pattern.compile("\\d+\\.\\d{2}").matcher(money_str).matches()){return;}
			if(money_str.replaceAll("\\..*", "").length()>7){return;}
			money_str = money_str + key;
			float tmp = Float.parseFloat(money_str);
			receive_money = (int) (tmp*100);
			display_money();
		}
		else if(key==DOT){
			if(Pattern.compile(".*\\..*").matcher(money_str).matches()){return;}
			if(money_str.length()>=8){return;}
			if(StringUtil.isNull(money_str)){money_str = "0.";receive_money=0;}
			else money_str = money_str + ".";
			display_money();
		}
		else if(key==DEL){
			if(StringUtil.isNull(money_str)){return;}
			money_str = money_str.substring(0, money_str.length()-1);
			if(StringUtil.isNull(money_str)){money_str = "";receive_money = 0;}
			else{
				float tmp = Float.parseFloat(money_str);
				receive_money = (int) (tmp*100);
			}
			display_money();
		}
	}
	
	private void display_money(){
		tv_receive_money.setText(money_str);
		if(receive_money<=real_money){return_money=0;}
		else{return_money = receive_money-real_money;}
		tv_return_money.setText(StringUtil.getMoneyString(return_money));
	}
	
	private void doSubmit_pre(){
		MyDialog dialog;
		MyDialog.Builder builder = new MyDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("确认已经收到现金 "+StringUtil.getMoneyString(real_money)+" 元");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				doSubmit();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				dialog.dismiss();
			}
		});
//		builder.create().setCancelable(false);
//		builder.create().show();
		dialog=builder.create();
//		dialog.setCancelable(false);
		dialog.show();
	}
	
	private void doSubmit(){
		
		final String client_sn = PayChannelChooseActivity.getNewClientSn(mActivity, EnumConsts.SqbPayChannel.CASH_MEMO.getType(), scanPayType);
		long t = new Date().getTime();
		
		saveLocalTradeDetail(t, client_sn);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sid", mApp.getLoginEntity().getSid());
		String memberCardNo = caculateMoneyEntity.getMemberCardNo();
		if(!StringUtil.isNull(memberCardNo)){params.put("cardNo", memberCardNo);}
		else{params.put("cardNo", "");}
		if(!StringUtil.isNull(password)){params.put("password", password);}
		else{params.put("password", "");}
		if(!StringUtil.isNull(couponSns)){params.put("couponSns", couponSns);}
		else{params.put("couponSns", "");}
		
		params.put("cash", caculateMoneyEntity.getRealMoney());
		params.put("bankAmount", "");
		params.put("couponCoverAmount", caculateMoneyEntity.getCouponCoverMoney());
		params.put("pointCoverAmount", caculateMoneyEntity.getPointCoverMoney());
		params.put("clientOrderNo", client_sn);
		//params.put("terminalNo", PayChannelChooseActivity.getActivateCodeId(this));
		
		//收钱吧
		if(scanPayType== EnumConsts.ScanPayType.SQB.getType()){
			params.put("activateCode", LocalParasUtils.getActivateCode(this));
			params.put("merchantNo", LocalParasUtils.getMerchantNo(this));
		}
		//富友
		else if(scanPayType== EnumConsts.ScanPayType.FUYOU.getType()){
			params.put("activateCode", mApp.getLoginEntity().getActivateCode());
			params.put("merchantNo", mApp.getLoginEntity().getFyMerchantNo());
		}
		
		params.put("t", t);
		params.put("transNo", "");
		params.put("authCode", "");
		params.put("pointAmount", pointAmount);
		TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); 
		String imei = tm.getDeviceId();
		params.put("serialNum", imei);
		params.put("payType", EnumConsts.SqbPayChannel.CASH_MEMO.getType());
		
		API.http_post(this, API.TRADE_LOG_UPLOAD, params, new HttpCallback<UploadResultEntity>(this) {
			@Override
			public void onSuccess(int statusCode, UploadResultEntity data) {
				updateOrderDetail(client_sn, data);
				openConfirmDialog();
			}

			@Override
			public void onFailure(int statusCode, String message) {
				openConfirmDialog();
				super.onFailure(statusCode, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<UploadResultEntity>() {
				};
			}
		});
		
	}
	
	private void updateOrderDetail(String clientOrderNo, UploadResultEntity data) {
		ContentValues cv = new ContentValues();
		String point_url = data.getPoint_url();
		String coupon_url = data.getCoupon();
		cv.put("point_url", StringUtil.isNull(point_url)?"":point_url);
		cv.put("coupon_url", StringUtil.isNull(coupon_url)?"":coupon_url);
		int point = data.getPoint();
		int pointCurrent = data.getPointCurrent();
		cv.put("point", point);
		cv.put("pointCurrent", pointCurrent);
		
		DataSupport.updateAll(OrderDetail.class, cv, "tradeOrderNo = ?", clientOrderNo);
	}
	
	private void saveLocalTradeDetail(long t, String tradeOrderNo){
		OrderDetail orderDetail = new OrderDetail();
		orderDetail.setTradeOrderNo(tradeOrderNo);
		orderDetail.setPayType(EnumConsts.SqbPayChannel.CASH_MEMO.getType());
		orderDetail.setTerminalSn(""+LocalParasUtils.getMerchantNo(this));
		orderDetail.setState(EnumConsts.SqbPayState.SUCCESS.getType());
		orderDetail.setTradeMoney(caculateMoneyEntity.getTradeMoney());
		orderDetail.setRealMoney(caculateMoneyEntity.getRealMoney());
		orderDetail.setMemberName(caculateMoneyEntity.getMemberName());
		//orderDetail.setTerminalName(LocalParasUtils.getTerminalName(mActivity));
		//orderDetail.setPointCost(caculateMoneyEntity.getPointCoverMoney());
		
		int couponCoverMoney = caculateMoneyEntity.getCouponCoverMoney();
		int pointCoverMoney = caculateMoneyEntity.getPointCoverMoney();
		String couponString = couponCoverMoney==0?"":("优惠券抵消"+StringUtil.getMoneyString(couponCoverMoney)+"元;");
		String pointString = pointCoverMoney==0?"":("积分抵消"+StringUtil.getMoneyString(pointCoverMoney)+"元;");
		if(!StringUtil.isNull(couponString)||!StringUtil.isNull(pointString)) orderDetail.setBenefit(pointString+couponString);
		
		orderDetail.setTradeTime(t);
		if(!StringUtil.isNull(password)){orderDetail.setPassword(password);}
		if(!StringUtil.isNull(couponSns)){orderDetail.setCouponSns(couponSns);}
		String memberCardNo = caculateMoneyEntity.getMemberCardNo();
		if(!StringUtil.isNull(memberCardNo)){orderDetail.setCardNo(memberCardNo);}
		orderDetail.setPointAmount(pointAmount);
		orderDetail.setCash(caculateMoneyEntity.getRealMoney());
		orderDetail.setBankAmount(0);
		
		//收钱吧
		if(scanPayType== EnumConsts.ScanPayType.SQB.getType()){
			orderDetail.setTerminalSn(LocalParasUtils.getActivateCode(mActivity));
			orderDetail.setMerchantNo(LocalParasUtils.getMerchantNo(mActivity));
			orderDetail.setActivateCode(LocalParasUtils.getActivateCode(mActivity));
			orderDetail.setTerminalName(LocalParasUtils.getTerminalName(mActivity));
		}
		//富友
		else if(scanPayType== EnumConsts.ScanPayType.FUYOU.getType()){
			orderDetail.setTerminalSn(mApp.getLoginEntity().getFyMerchantNo());
			orderDetail.setMerchantNo(mApp.getLoginEntity().getFyMerchantNo());
			orderDetail.setActivateCode(mApp.getLoginEntity().getActivateCode());
			orderDetail.setTerminalName(mApp.getLoginEntity().getFyMerchantName());
		}
		
		TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); 
		orderDetail.setSerialNum(tm.getDeviceId());
		orderDetail.save();
	}
	
	private void openConfirmDialog(){
		MyDialog.Builder builder = new MyDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("现金收款成功！");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
				startActivity(new Intent(mActivity, PayMoneyInputActivity.class));
				
				Intent intent = new Intent(PayMoneyInputActivity.RECEIVER_CLEAN_DATA_TAG);
				intent.putExtra(PayMoneyInputActivity.NOTIFY_CODE_TAG, PayMoneyInputActivity.CLEAN_DATA);
		        sendBroadcast(intent);
		        
			}
		});
		builder.create().show();
	}
	
}
